import { Clock, BadgeInfo, Link2, Star } from "lucide-preact";
import { useRef, useEffect, useState } from "preact/hooks";
import { stopPropagation } from "../utilities";
import { settings } from "../settings";
import { hasIme, findFavo, isPortrait, wordSignal } from "../signals";
import { mergeSuggests } from "../suggest";

const icons = {
  link: <Link2 />,
  history: <Clock />,
  suggest: <BadgeInfo />,
  favo: <Star />,
};

const clickAction = {
  favo: 15,
  link: 16,
  history: 9,
  suggest: 9,
};

function getSugHigh(port, ime) {
  const key = `suggestHeight${port ? "P" : "L"}${ime ? "K" : ""}`;
  return settings.value.searchPart[key];
}

const Suggestion = ({ onInput, extCount }) => {
  const sugRef = useRef(null);
  const [data, setData] = useState([]);

  useEffect(() => {
    mergeSuggests(wordSignal.value).then((result) => setData(result));
    if (sugRef.current) {
      sugRef.current.scrollTop = 0;
    }
  }, [extCount, wordSignal.value, sugRef]);

  return (
    <div
      ref={sugRef}
      style={{
        positionAnchor: "--bar",
        top: "anchor(bottom)",
        justifySelf: "anchor-center",
        maxHeight: getSugHigh(isPortrait.value, hasIme.value),
      }}
      class={`dropdown-content rounded-box h-max overflow-y-scroll shadow-sm ${
        settings.value.searchPart.showSuggest && !findFavo.value ? "" : "hidden"
      }`}
      onTouchStart={stopPropagation}
      onTouchMove={stopPropagation}
      onTouchEnd={stopPropagation}
    >
      <menu class="menu menu-md bg-base-200 z-1 w-(--search-bar-width) p-[0] **:truncate">
        {data.map((sug) => (
          <li key={sug.word} class="w-full px-3 first:pt-3 last:pb-3">
            <button
              class="flex text-nowrap"
              onClick={() =>
                onInput(
                  clickAction[sug.type],
                  sug.type === "favo" ? sug : sug.word,
                )
              }
              onContextMenu={() =>
                onInput(
                  `${sug.type}Press`,
                  sug.type === "favo" ? sug : sug.word,
                )
              }
            >
              {settings.value.searchPart.suggestIcon ? (
                <i class="size-5 flex-none *:size-5">{icons[sug.type]}</i>
              ) : (
                void 0
              )}
              <span class="w-10 grow pl-1">{sug.word}</span>
              {typeof sug.flag == "string" ? (
                <span class="badge badge-xs w-10 flex-none">{sug.flag}</span>
              ) : (
                void 0
              )}
            </button>
          </li>
        ))}
      </menu>
    </div>
  );
};

export default Suggestion;
